﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.CodeDom;

namespace ConsoleApplication
{
    /// <summary>
    /// Complie code
    /// </summary>
    public class CodeCompiler
    {
        /// <summary>
        /// Do compile
        /// </summary>
        /// <param name="referencesList">references dll</param>
        /// <param name="assemblyName">out assembly name</param>
        /// <param name="codeSource">code to be compiled</param>
        public static void Compiler(List<string> referencesList, string assemblyName, string codeSource)
        {
            CSharpCodeProvider codeProvider = new CSharpCodeProvider();
            ICodeCompiler icc = codeProvider.CreateCompiler();
            System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
            parameters.GenerateExecutable = false;
            parameters.OutputAssembly = assemblyName;
            foreach (var item in referencesList)
            {
                parameters.ReferencedAssemblies.Add(item);
            }
            CompilerResults results = icc.CompileAssemblyFromSource(parameters, codeSource);
            string compilerMsg = string.Empty;
            if (results.Errors.Count > 0)
            {
                foreach (CompilerError CompErr in results.Errors)
                {
                    compilerMsg +=
                        "Line number " + CompErr.Line +
                        ", Error Number: " + CompErr.ErrorNumber +
                        ", '" + CompErr.ErrorText + ";" +
                        Environment.NewLine + Environment.NewLine;
                }
            }
            Console.Write(compilerMsg);
        }
        /// <summary>
        /// Convert a normal assembly to wcf contract dll
        /// </summary>
        /// <param name="fromAssemblyName">assembly to be converted</param>
        /// <param name="targetAssemlyName">result assembly</param>
        public static void GenerateContract(string fromAssemblyName, string targetAssemlyName)
        {
            CSharpCodeProvider codeProvider = new CSharpCodeProvider();
            ICodeCompiler icc = codeProvider.CreateCompiler();
            CompilerParameters param = new CompilerParameters();
            param.GenerateExecutable = false;
            param.GenerateInMemory = false;
            param.OutputAssembly = targetAssemlyName;
            CompilerResults results = icc.CompileAssemblyFromFile(param, fromAssemblyName);

            string MyVariable = "myVariable";
            string GetType = typeof(System.Object).GetMember("GetType")[0].Name;
            CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression(MyVariable), GetType);
            
        }
    }
}
